<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <!-- 前 K 个高频元素 -->
    <script>
      var topKFrequent = function (nums, k) {
        let map = new Map()
        nums.forEach(n => {
          map.set(n, map.has(n) ? map.get(n) + 1 : 1)
        })
        // 首先将字典转成数组，然后对数组中的第二个元素（频度）从小到大排序
        let list = Array.from(map).sort((a, b) => b[1] - a[1])
        // 截取频率前k高的元素
        return list.slice(0, k).map(n => n[0])
      }
      console.log(topKFrequent([1, 1, 1, 2, 2, 3], 2))
    </script>
  </body>
</html>
